using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Threading;
using System.Globalization;

namespace miciv
{
    public class XmlTraverser
    {
        public delegate bool StartElementEventHandler(string _strName, XmlAttributeCollection _xmlAttributes);
        public delegate bool EndElementEventHandler(string _strName);

        public event StartElementEventHandler StartElement;
        public event EndElementEventHandler EndElement;

        protected XmlElement m_xmlStart;

        public XmlTraverser(XmlElement _xmlElement)
        {
            this.m_xmlStart = _xmlElement;
        }

        public void Traverse()
        {
            try
            {
                CultureInfo currCI = CultureInfo.CurrentCulture;
                Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
                Traverse(this.m_xmlStart);
                Thread.CurrentThread.CurrentCulture = currCI;
            }
            catch (LuaInterface.LuaException e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
            }
            catch (System.Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
            }
        }

        protected bool Traverse(XmlElement _xmlElement)
        {
            bool bResult = true;
            foreach (XmlNode xmlChildNode in _xmlElement.ChildNodes)
            {
                XmlElement xmlChildElement = xmlChildNode as XmlElement;
                if (null != xmlChildElement)
                {
                    if (null != StartElement)
                    {
                        bResult = StartElement(xmlChildElement.Name, xmlChildElement.Attributes);
                    }
                    if (false == bResult)
                    {
                        break;
                    }
                    Traverse(xmlChildElement);
                    if (null != EndElement)
                    {
                        EndElement(xmlChildElement.Name);
                    }
                }
            }
            return bResult;
        }
    }
}
